import { computed, readonly, ref } from 'vue'
import { AD_TYPE, COLUMN_SHAPE, MEDIA_SHAPE } from '@/constant'
import { MEDIA_TYPE } from '@/constant/publish'

const MAX_COLUMNS = 12

/**
 * 用於建立 MediaRow 的帖子 grid cols 長度資料
 */
export const useFeedCols = () => {
  // grid rows 二維陣列
  // 其中每個元素會是一個長得像以下範例的陣列
  // [{ item, cols: 4}, { item, cols: 4}, { item, cols: 4}]
  // [{ item, cols: 4}, { item, cols: 8}]
  // [{ item, cols: 8}, { item, cols: 4}]
  // 代表每個 row 長度加總最多 12
  const rows = ref([])

  // 展開每欄的 item 成為一維陣列
  const itemList = computed(() => rows.value.reduce((a, c) => a.concat(c.map((o) => o.item)), []))

  // 展開每欄的 cols 成為一維陣列
  const colsList = computed(() => rows.value.reduce((a, c) => a.concat(c.map((o) => o.cols)), []))

  /**
   * 輸入新資料進來與原有資料持續合併排序
   *
   * @param {*} datas 新的一批資料
   */
  function input(datas) {
    if (rows.value.length > 0) {
      const lastRow = rows.value.splice(rows.value.length - 1, 1)[0]
      rows.value.push(...createRows(datas, lastRow))
    } else {
      rows.value.push(...createRows(datas))
    }
  }

  /**
   * 清空資料
   */
  function reset() {
    rows.value = []
  }

  return {
    rows: readonly(rows),
    itemList,
    colsList,
    input,
    reset,
  }
}

/**
 * 計算每個column的cols屬性，並重新分組
 *
 * @param {Array} datas 新資料
 * @param {Array} lastRow 已存在 rows 中的最後一個 row
 * @returns Array
 */
function createRows(datas, lastRow = []) {
  const columns = datas.map((data) => ({ item: data, cols: cols(data) }))
  const result = []

  if (rowLen(lastRow) === MAX_COLUMNS) {
    result.push(lastRow)
    lastRow = []
  }

  columns.forEach((column) => {
    let pushCount = 0

    const rl = rowLen(lastRow)
    if (rl + column.cols <= MAX_COLUMNS) {
      pushCount = lastRow.push(column)
    } else {
      if (rl + COLUMN_SHAPE.LONG <= MAX_COLUMNS) {
        column.cols = COLUMN_SHAPE.LONG
        pushCount = lastRow.push(column)
      }
    }

    if (rowLen(lastRow) === MAX_COLUMNS) {
      result.push(lastRow)
      lastRow = []
      if (pushCount === 0) lastRow.push(column)
    }
  })

  if (lastRow.length > 0) result.push(lastRow)

  return result
}

function cols(item) {
  switch (item.type) {
    case MEDIA_TYPE.VIDEO:
      return item.shape === MEDIA_SHAPE.WIDE ? COLUMN_SHAPE.WIDE : COLUMN_SHAPE.LONG
    case MEDIA_TYPE.IMAGE:
      if (typeof item.img_width === 'number' && typeof item.img_height === 'number') {
        return item.img_width / item.img_height > 1 ? COLUMN_SHAPE.WIDE : COLUMN_SHAPE.LONG
      } else {
        return COLUMN_SHAPE.LONG
      }
    case AD_TYPE.PHOTO:
      if (typeof item.width === 'number' && typeof item.height === 'number') {
        return item.width / item.height > 1 ? COLUMN_SHAPE.WIDE : COLUMN_SHAPE.LONG
      } else {
        return COLUMN_SHAPE.LONG
      }
    default:
      return COLUMN_SHAPE.LONG
  }
}

function rowLen(row) {
  return row.reduce((a, c) => a + c.cols, 0)
}
